package com.gzw.jackyweather.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.gzw.jackyweather.Contans;
import com.gzw.jackyweather.WeatherActivity;
import com.gzw.jackyweather.db.CityManger;
import com.gzw.jackyweather.db.CityWeatherInfo;
import com.gzw.jackyweather.gson.Weather;
import com.gzw.jackyweather.util.HttpUtil;
import com.gzw.jackyweather.util.Utility;

import org.json.JSONException;
import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 后台每8小时自动更新天气的service
 */
public class AutoUpdateService extends Service {
    public AutoUpdateService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        //更新天气
        updateWeather();
        //更新图片
//        updateBingPic();
        AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
        int anHour = 8 * 60 * 60 * 1000;//设置每8小时更新一次
        long triggerAtTime = SystemClock.elapsedRealtime() + anHour;
        Intent i = new Intent(this, AutoUpdateService.class);
        PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
        manager.cancel(pi);
        manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pi);
        return super.onStartCommand(intent, flags, startId);
    }

    private void updateWeather() {

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        String weatherStr = sp.getString("weather", null);
        if (weatherStr != null) {
            Weather weather = Utility.handleWeatherResponse(weatherStr);
            String weatherId = weather.basic.weatherId;
            String weatherUrl = "http://guolin.tech/api/weather?cityid=" + weatherId +
                    Contans.KEY;

            HttpUtil.sendOkHttpRequest(weatherUrl, new Callback() {

                @Override
                public void onResponse(Call call, Response response) throws IOException {

                    String responseText = response.body().string();
                    Weather weather = Utility.handleWeatherResponse(responseText);

                    if (weather != null && "ok".equals(weather.status)) {

                        List<CityWeatherInfo> infos = DataSupport.where("weather_id=?", weather.basic.weatherId).find(CityWeatherInfo.class);
                        //查询数据库中的数据，如果没有就添加，如果有就更新
                        if (infos.size() != 0) {
                            ContentValues values = new ContentValues();
                            values.put("weather_info", responseText);
                            DataSupport.updateAll(CityWeatherInfo.class, values, "weather_id = ?", weather.basic.weatherId);
                        } else {
                            CityWeatherInfo info = new CityWeatherInfo();
                            info.setWeather_id(weather.basic.weatherId);
                            info.setWeather_info(responseText);
                            info.save();
                        }
                        ;

                        List<CityManger> cityMangers = DataSupport.where("weather_id = ?", weather.basic.weatherId).find(CityManger.class);
                        if (cityMangers.size() == 0) {
                            //说明没有数据，添加一条数据
                            CityManger manger = new CityManger();
                            manger.setDefault(true);
                            manger.setWeather_id(weather.basic.weatherId);
                            manger.setCityName(weather.basic.cityName);
                            manger.setDegree(weather.now.temperature + "℃");
                            manger.setWeather_info(weather.now.more.info);
                            manger.save();

                        } else {
                            //有数据，更新一条数据
                            ContentValues values = new ContentValues();
                            values.put("degree", weather.now.temperature + "℃");
                            values.put("cityName", weather.basic.cityName);
                            values.put("weather_info", weather.now.more.info);
                            DataSupport.updateAll(CityManger.class, values, "weather_id = ?", weather.basic.weatherId);
                        }

                    }
                }

                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }
            });

        }

    }

    private void updateBingPic() {

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        String bingPic = sp.getString("bing_pic", null);
        if (bingPic.substring(0, 4).equals("http")) {
//            String requestBingPic = "http://guolin.tech/api/bing_pic/";
            HttpUtil.sendOkHttpRequest(Contans.IMG_URL, new Callback() {
                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    //保存请求的图片
                    //保存请求的图片
                    final String json = response.body().string();
                    String imgurl = null;
                    try {
                        JSONObject jsonObject = new JSONObject(json);
                        imgurl = jsonObject.getString("img");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    final String bingPic = imgurl;
                    SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(AutoUpdateService.this).edit();
                    edit.putString("bing_pic", bingPic);
                    edit.apply();
                }

                @Override
                public void onFailure(Call call, IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }
}
